from wtforms import StringField, IntegerField, BooleanField
from wtforms.validators import ValidationError, DataRequired, Length

from app.form.base_form import BaseForm
from app.models import BlogUser


class UserUpdateForm(BaseForm):
    """用户修改校验
    """
    id = IntegerField(validators=[DataRequired('用户ID不能为空')])
    username = StringField(validators=[Length(4, 32, message="用户名4~32个字符")])
    avatar = StringField()
    super_user = BooleanField()
    active_user = BooleanField()
    staff_user = BooleanField()

    def validate_id(form, field):
        """验证用户名是否存在"""
        user = BlogUser.query.get(field.data)
        if user is None:
            raise ValidationError(message="用户不存在")

    def validate_username(form, field):
        """验证用户名是否存在
        1.根据用户名找到用户
        2.找到的用户不是修改的用户
        """
        user = BlogUser.query.filter_by(username=field.data).first()
        if user is not None and not form.id.data == user.id:
            raise ValidationError(message="用户名已存在")
